<?php 

import('@.com.99ebc.lib.Error');
import('@.com.99ebc.lib.File');
import('@.com.99ebc.lib.Xml');

import("ORG.Util.Image");


class MediaModel extends Model{

    //表字段配置
    protected $fields   = array(
                                'media_id',
                                'media_name',
                                'sort_loc',
                                'media_type',
                                'media_url',
                                'media_desc',
                                'image_path',
                                'edit_time',
                                '_pk' => 'media_id',
                                '_autoinc' => true
                            );
    //自动验证
    protected $_validate    = array(
        array('media_name', 'require', '名称不能为空！'),
        array('sort_loc', 'number', '排序编号必须是数字！',2),
        array('jump_url', 'url', '跳转链接无效！',2)
    );

    //自动完成
    protected $_auto        = array(
        array('edit_time', 'mktime', 3, 'function')
    );

    protected static $orderFields = 'sort_loc';

    protected static $xmlFields   = 'media_name, media_type, image_path, media_url, media_desc';

    protected $_imageTypes;
    protected $_imageSize;
    protected $_uploadDir;

    protected $_countWhere;

    protected $_error;

    //默认详细信息里显示的图片类型
    protected static $infoImgType     = '_s';
    //格式:width, height, type, interlace, 后缀
    protected static $thumbImgInfo  = array(
        '_s' => array('w' => 100, 'h' => 100, 't' => 'jpg', 'i' => true),
        '_m' => array('w' => 200, 'h' => 200, 't' => 'jpg', 'i' => true),
    );

    //XML配置参数
    protected static $xmlFilePath   = 'xml/media.xml';

    protected static $childNode    = '
<window type="%s" %s>
    <title><![CDATA[<b>%s</b>]]></title>
    <asset>%s</asset>
    <info><![CDATA[%s]]></info>
</window>';
    protected static $rootNode     = '<site>
    %s
</site>';

    public function __construct() {
        parent::__construct();

        $this->_imageSize   = 20;
        $this->_imageTypes  = array('jpg', 'jpeg', 'png', 'gif', 'bmp', 'flv', 'swf');
        $this->_uploadDir   = 'Public/default/uploadfiles/media';
        $this->_error       = new Error(); 
    }

    //得到记录总数
    public function getCountRecords() {
        return $this->where($this->_countWhere)->count();
    }
    
    //搜索方法
    public function searchMedia($page = 0, $keyword, $perPage = 10) {
        if(preg_match('/^\/+\d+$/', $keyword)) {
            $whereSearch  = '`media_id` = ' . strtr($keyword, array('/' => ''));
        } else {
            $whereSearch  = '`media_name` like \'%' . $keyword . '%\'';
        }
        $this->_countWhere  = $whereSearch;

        return $this->seeMedia($page, $whereSearch, $perPage);
    }

    //查看列表方法 
    public function seeMedia($page = 0, $whereMedia = '', $perPage = 10) {
        return $this->where($whereMedia)->order('sort_loc')->limit($perPage)->page($page)->select();
    }

    //查看记录详细信息方法
    public function infoMedia($recordId) {
        $record     = $this->where('`media_id` = ' . $recordId)->find();
        if(!empty($record['image_path'])) {
            $record['image_path_small']     = $this->genThumbImageName($record['image_path']) . self::$infoImgType . '.' . self::$thumbImgInfo[self::$infoImgType]['t']; 
        }
        return $record;
    }

    //编辑记录方法
    public function editMedia($recordId) {
        if(false === $this->uploadFile()) {
            return $this->_error->getErrorInfo();
        }
        if(isset($_POST['del_image'])) {
            if(!empty($_POST['del_image'])) {
                if(false === $this->deleteFile($_POST['old_image_path'])) {
                    Logger::log('删除文件失败！' . $_POST['old_image_path']);
                } else {
                    $_POST['image_path']= '';
                }
            } else {
                $_POST['image_path']    = $_POST['old_image_path'];
            }
        }
        if(false === $this->create()) {
            return $this->getError();
        }
        if(false === $this->save()) {
            return $this->getError();
        }

        return true;
    }

    //添加记录方法
    public function addMedia() {
        if(false === $this->uploadFile()) {
            return $this->_error->getErrorInfo();
        }
        if(false === $this->create()) {
            return $this->getError();
        }
        if(false === $this->add()) {
            return false;
            return $this->getError();
        }

        return true;
    }

    //删除记录方法
    public function deleteMedia($recordId) {
        
        return $this->quickDeleteMedia(array($recordId));
    }

    //快捷操作：删除记录
    public function quickDeleteMedia(array $recordIds){
        $this->quickDeleteImageMedia($recordIds);
        $whereStr   = $this->genWhereIn('media_id', $recordIds);

        return $this->where($whereStr)->delete();
    }

    //快捷操作：删除记录相关文件
    public function quickDeleteImageMedia(array $recordIds) {
        $whereStr   = $this->genWhereIn('media_id', $recordIds) . ' AND (`image_path` !=\'\' AND `image_path` IS NOT NULL)';
        $recordList = $this->where($whereStr)->field('media_id, image_path')->select();

        if(empty($recordList)) {
            return ture;
        }
        $whereStr   = '`media_id` IN (';
        foreach($recordList as $record) {
            if($this->deleteFile($record['image_path'])) {
                Logger::log('快捷删除文件失败！' . $record['image_path']);
            }
            $whereStr   .= $record['media_id'] . ', ';
        }
        $whereStr    .= '-1)';

        return $this->where($whereStr)->setField('image_path', '');
    }

    //生成FLASH调用的XML文件
    public function xmlMedia() {
        $perPage        = 10;
        $totalRows      = $this->getCountRecords();
        $totalPage      = ceil($totalRows / $perPage);
        for($page = 0; $page < $totalPage; $page ++) {
            $recordList     = $this->getXmlRecordList($page, $perpage);
            $xmlContent     .= $this->genXmlContent($recordList);
        }
        if(false === $this->writeXml($xmlContent)) {
            Logger::log('写入XML内容失败！' . __CLASS__);
        }

        return true;
    }

    //得到XML的数据集
    protected function getXmlRecordList($page, $perpage = 10) {
        return $this->field(self::$xmlFields)->order(self::$orderFields)->page($page, $perpage)->select();
    }

    //写入XML文件内容
    protected function writeXml($childNode) {
        $xmlContent     = sprintf(self::$rootNode, $childNode);
        $xml    = new Xml(self::$xmlFilePath, $xmlContent);

        return  $xml->save();

    }

    //生成主页的XML内容
    protected function genXmlContent($recordList) {
        if(empty($recordList)) {
            return '';
        }
        foreach($recordList as $record) {
            $record     = $this->formatRecordToXmlContent($record);
            $xmlContent .= vsprintf(self::$childNode, $record);
        }

        return $xmlContent;
    }

    protected function formatRecordToXmlContent($record) {
        if(!empty($record['image_path'])) {
            $record['image_path']   = $this->_uploadDir . '/' . $record['image_path'];
        }
        switch($record['media_type']) {
            case 1:
                $data[]     = 'image';
                $data[]     = '';
                $data[]     = $record['media_name'];
                $data[]     = $record['image_path'];
                $data[]     = $record['media_desc'];
                break;
            case 2:
                $data[]     = 'swf';
                $data[]     = 'picture="' . $record['image_Path'] . '"';
                $data[]     = $record['media_name'];
                $data[]     = $record['media_url'];
                $data[]     = $record['media_desc'];
                break;
            case 3:
                $data[]     = 'video';
                $data[]     = 'picture="' . $record['image_Path'] . '"';
                $data[]     = $record['media_name'];
                $data[]     = $record['media_url'];
                $data[]     = $record['media_desc'];
                break;
        }

        return $data;
    }

    //生成WhereIn条件语句
    protected function genWhereIn($field, array $values) {
        return '`' . $field . '` IN (' . implode(',', $values) . ', -1)';
    }

    //上传文件方法
    protected function uploadFile() {
        if(!empty($_FILES['image_path']['name'])) {
            $uploadFile     = new UploadFile($_FILES['image_path'],
                                        $this->_uploadDir,
                                        $this->_imageTypes,
                                        $this->_imageSize);
            if(false === $uploadFile->upload()) {
                $this->_error->setErrorInfo($uploadFile->getError());
                return false;
            }
            $arrPath    = explode('/', $uploadFile->getUploadFilePath());
            $_POST['image_path']    = array_pop($arrPath);
            $_POST['image_path']    = array_pop($arrPath) . '/' . $_POST['image_path'];
            //生成缩略图
            $this->genThumbImage($uploadFile->getUploadFilePath());
            
            return true;
        }

        return true;
    }

    //生成缩略图
    protected function genThumbImage($srcFilePath) {
        $thumbImgName  = $this->genThumbImageName($srcFilePath);
        foreach(self::$thumbImgInfo as $kind => $thumbInfo) {
            $thumbImgPath   = $thumbImgName . $kind . '.' . $thumbInfo['t'];
            $genResult      = Image::thumb($srcFilePath, $thumbImgPath, $thumbInfo['t'], $thumbInfo['w'], $thumbInfo['h'], $thumbInfo['i']);
            if(!$genResult) {
               //log 
            }
        } 
    }

    //得到缩略图的路径及文件名
    public function genThumbImageName($srcFilePath) {
        return mb_substr($srcFilePath , 0, strrpos($srcFilePath, '.'), 'utf-8');
    }

    //这个将会作为一个interface
    protected function deleteFile($filePath) {
        if(!empty($filePath)) {
            $this->delThumbImageFile($filePath);
            return LittleTools::deleteFile($filePath, $this->_uploadDir);
        }

        return true;
    }

    //删除相关缩略图
    protected function delThumbImageFile($filePath) {
        $thumbImgName  = $this->genThumbImageName($filePath);
        foreach(self::$thumbImgInfo as $kind => $thumbInfo) {
            $thumbImgPath   = $thumbImgName . $kind . '.' . $thumbInfo['t'];
            LittleTools::deleteFile($thumbImgPath, $this->_uploadDir);
        } 
    }

    public function getUploadDir() {
        return preg_replace('/public/i', '', $this->_uploadDir);
    }

    public function uploadMedia() {
        $uploadItems     = array(
            'logo_upload' => 'uploadLogo',
            'bg_upload_1' => 'uploadBgFirst',
        );
        $data   = array(
            'status' => 0,
            'path' => '',
            'msg' => ''
        );
        if(empty($_FILES)) {
            $data['msg']    = '文件不能为空！';
            Logger::log($data['msg']);

            return $data;
        }
        foreach($_FILES as $key => $uploadInfo) {
            if(!array_key_exists($key, $uploadItems)) {
                $data['msg'] = '非法操作!';
                Logger::log(var_export($data, true));
            }
            $this->loadXmlFile();
            $actionName     = $uploadItems[$key];
            $targetPath     = $this->$actionName();
            if(empty($targetPath)) {
                $data['msg'] = '上传失败！';
                Logger::log($data['msg']);
            } else {
                $this->_xml->asXml(self::$xmlFilePath);
                $data['status'] = 0;
                $data['msg']    = '上传成功！';
                $data['path']   = preg_replace('/default\//i', '', $this->genThumbImagePath($targetPath));
                Logger::log(var_export($data, true));
            }
        }

        return $data;
    }

    protected function uploadLogo() {
        return $this->commUpload('logo_upload', 'myLogo');
    }

    protected function uploadBgFirst() {
        return $this->commUpload('bg_upload_1', 'backgroundImage1');
    }

    protected function commUpload($fileItem, $item) {
        $uploadFile = $_FILES[$fileItem];
        $oldFile    =  $this->_xml->mods[$item];
        $upload   = $this->uploadFIle($uploadFile);
        if(empty($upload)) {
            return false;
        } else {
            if(!empty($oldFile)) {
                $this->deleteFile($oldFile);
            }
            $this->_xml->mods[$item]    = $upload;
        }

        return $upload;
    }

    //得到模块的类型ID
    public function getModelTypeId() {
        if(empty($this->_modelTypeId)) {
            return $_GET['type'];
        }

        return $this->_modelTypeId;
    }

}

?>
